package com.jn.zhinongbao.adapter;

import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.example.supportingagriculturaltreasures.bean.Product;
import com.example.supportingagriculturaltreasures.bean.User;
import com.example.supportingagriculturaltreasures.database.DatabaseHelper;
import com.example.supportingagriculturaltreasures.provider.AgriculturalContentProvider;
import com.example.supportingagriculturaltreasures.utils.PreferenceManager;
import com.google.android.material.textfield.TextInputEditText;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.UUID;

public class PublishProductActivity extends AppCompatActivity {

    private static final int REQUEST_IMAGE_PICK = 1001;
    private static final int REQUEST_CAMERA_PERMISSION = 1002;

    private TextInputEditText etProductName, etProductPrice, etProductLocation, etContactPhone;
    private Spinner spinnerCategory;
    private ImageView ivProductImage;
    private Button btnSelectImage, btnPublish;
    
    private PreferenceManager preferenceManager;
    private DatabaseHelper databaseHelper;
    private User currentUser;
    private String selectedImagePath;

    // 分类选项
    private String[] categories = {"水果蔬菜", "米面粮油", "农资农具"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_product);

        // 设置ActionBar
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("发布货品");
        }

        initViews();
        initData();
        setupSpinner();
        setupClickListeners();
        loadUserData();
    }

    private void initViews() {
        etProductName = findViewById(R.id.et_product_name);
        etProductPrice = findViewById(R.id.et_product_price);
        etProductLocation = findViewById(R.id.et_product_location);
        etContactPhone = findViewById(R.id.et_contact_phone);
        spinnerCategory = findViewById(R.id.spinner_category);
        ivProductImage = findViewById(R.id.iv_product_image);
        btnSelectImage = findViewById(R.id.btn_select_image);
        btnPublish = findViewById(R.id.btn_publish);
    }

    private void initData() {
        preferenceManager = new PreferenceManager(this);
        databaseHelper = new DatabaseHelper(this);
    }

    private void setupSpinner() {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, 
                android.R.layout.simple_spinner_item, categories);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerCategory.setAdapter(adapter);
    }

    private void setupClickListeners() {
        btnSelectImage.setOnClickListener(v -> selectImage());
        btnPublish.setOnClickListener(v -> publishProduct());
    }

    private void loadUserData() {
        int userId = preferenceManager.getCurrentUserId();
        if (userId != -1) {
            currentUser = databaseHelper.getUserById(userId);
            if (currentUser != null) {
                // 检查是否是商家
                if (!currentUser.isMerchant()) {
                    Toast.makeText(this, "只有商家才能发布货品", Toast.LENGTH_SHORT).show();
                    finish();
                    return;
                }
                
                if (currentUser.getPhone() != null) {
                    etContactPhone.setText(currentUser.getPhone());
                }
                
                // 调试信息
                String debugInfo = String.format("用户: %s, 角色: %s, 店铺: %s", 
                        currentUser.getUsername(), 
                        currentUser.getRoleText(),
                        currentUser.getShopName() != null ? currentUser.getShopName() : "未设置");
                Toast.makeText(this, debugInfo, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "数据库中未找到用户信息，ID：" + userId, Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(this, "未找到登录用户ID，请重新登录", Toast.LENGTH_LONG).show();
        }
    }

    private void selectImage() {
        // 检查并申请权限
        if (!hasStoragePermission()) {
            requestStoragePermission();
            return;
        }

        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, REQUEST_IMAGE_PICK);
    }

    /**
     * 检查是否有存储权限（适配所有API版本）
     */
    private boolean hasStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13+ 使用新的分段权限
            return ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES) 
                    == PackageManager.PERMISSION_GRANTED;
        } else {
            // Android 12及以下使用传统权限
            return ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) 
                    == PackageManager.PERMISSION_GRANTED;
        }
    }

    /**
     * 申请存储权限（适配所有API版本）
     */
    private void requestStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13+ 申请新的分段权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_MEDIA_IMAGES},
                    REQUEST_CAMERA_PERMISSION);
        } else {
            // Android 12及以下申请传统权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    REQUEST_CAMERA_PERMISSION);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == REQUEST_IMAGE_PICK && resultCode == RESULT_OK && data != null) {
            Uri selectedImageUri = data.getData();
            if (selectedImageUri != null) {
                // 将图片复制到应用私有存储
                String copiedImagePath = copyImageToPrivateStorage(selectedImageUri);
                if (copiedImagePath != null) {
                    selectedImagePath = copiedImagePath;
                    // 使用Glide加载复制后的图片
                    Glide.with(this)
                            .load(new File(copiedImagePath))
                            .placeholder(R.drawable.ic_launcher_foreground)
                            .error(R.drawable.ic_launcher_foreground)
                            .into(ivProductImage);
                } else {
                    Toast.makeText(this, "图片处理失败，请重新选择", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    /**
     * 将选择的图片复制到应用私有存储
     */
    private String copyImageToPrivateStorage(Uri imageUri) {
        try {
            // 创建应用私有存储目录
            File imagesDir = new File(getFilesDir(), "product_images");
            if (!imagesDir.exists()) {
                imagesDir.mkdirs();
            }
            
            // 生成唯一的文件名
            String fileName = "product_" + UUID.randomUUID().toString() + ".jpg";
            File destinationFile = new File(imagesDir, fileName);
            
            // 复制图片
            InputStream inputStream = getContentResolver().openInputStream(imageUri);
            if (inputStream != null) {
                FileOutputStream outputStream = new FileOutputStream(destinationFile);
                
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }
                
                outputStream.close();
                inputStream.close();
                
                return destinationFile.getAbsolutePath();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                selectImage();
            } else {
                String permissionName = Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU ? 
                        "媒体图片" : "存储";
                Toast.makeText(this, "需要" + permissionName + "权限才能选择图片", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void publishProduct() {
        // 获取输入数据
        String productName = etProductName.getText().toString().trim();
        String priceStr = etProductPrice.getText().toString().trim();
        String location = etProductLocation.getText().toString().trim();
        String contactPhone = etContactPhone.getText().toString().trim();
        String category = (String) spinnerCategory.getSelectedItem();

        // 验证输入
        if (TextUtils.isEmpty(productName)) {
            etProductName.setError("请输入货品名称");
            etProductName.requestFocus();
            return;
        }

        if (TextUtils.isEmpty(priceStr)) {
            etProductPrice.setError("请输入货品价格");
            etProductPrice.requestFocus();
            return;
        }

        double price;
        try {
            price = Double.parseDouble(priceStr);
            if (price <= 0) {
                etProductPrice.setError("价格必须大于0");
                etProductPrice.requestFocus();
                return;
            }
        } catch (NumberFormatException e) {
            etProductPrice.setError("请输入有效的价格");
            etProductPrice.requestFocus();
            return;
        }

        if (TextUtils.isEmpty(location)) {
            etProductLocation.setError("请输入发货地");
            etProductLocation.requestFocus();
            return;
        }

        if (TextUtils.isEmpty(contactPhone)) {
            etContactPhone.setError("请输入联系电话");
            etContactPhone.requestFocus();
            return;
        }

        if (currentUser == null) {
            Toast.makeText(this, "用户信息获取失败，请重新登录", Toast.LENGTH_SHORT).show();
            // 跳转到登录页面
            Intent loginIntent = new Intent(this, LoginActivity.class);
            loginIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(loginIntent);
            finish();
            return;
        }

        // 验证商家信息完整性
        String shopName = currentUser.getShopName();
        if (shopName == null || shopName.trim().isEmpty()) {
            shopName = currentUser.getUsername() + "的店铺"; // 默认店铺名
        }

        // 创建产品对象
        Product product = new Product(productName, price, location, contactPhone, 
                selectedImagePath, category, shopName, 
                currentUser.getUsername(), currentUser.getId());

        // 使用ContentProvider保存产品
        ContentValues values = new ContentValues();
        values.put("name", product.getName());
        values.put("price", product.getPrice());
        values.put("location", product.getLocation());
        values.put("contact_phone", product.getContactPhone());
        values.put("image_url", product.getImageUrl());
        values.put("category", product.getCategory());
        values.put("shop_name", product.getShopName());
        values.put("merchant_name", product.getMerchantName());
        values.put("merchant_id", product.getMerchantId());
        values.put("likes", 0);
        values.put("create_time", System.currentTimeMillis());

        Uri resultUri = getContentResolver().insert(AgriculturalContentProvider.CONTENT_URI_PRODUCTS, values);
        
        if (resultUri != null) {
            Toast.makeText(this, "货品发布成功！", Toast.LENGTH_SHORT).show();
            finish();
        } else {
            Toast.makeText(this, "货品发布失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
} 